package web.servlet;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;

@WebServlet("/user")
public class UserServlet extends BaseServlet{

    private UserService userService = new UserServiceImpl();

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //判断是否要记住用户名
        String remember = req.getParameter("remember");

        Cookie cookie = new Cookie("username",username);
        Cookie statusCookie = new Cookie("rememberStatus","true");
        if ("true".equals(remember)){
            //要记住用户名
            cookie.setMaxAge(60*60*24*7); //7天
            statusCookie.setMaxAge(60*60*24*7); //7天
        }else{
            //取消记住用户名
            cookie.setMaxAge(0);
            statusCookie.setMaxAge(0);
        }

        cookie.setPath(req.getContextPath());
        statusCookie.setPath(req.getContextPath());

        resp.addCookie(cookie);
        resp.addCookie(statusCookie);

        //登录逻辑
        User user = userService.login(username,password);
        if (user == null){
            //登录失败
            req.setAttribute("error","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else{
            //登录成功
            //将登陆后的用户对象存入session中
            req.getSession().setAttribute("user",user);
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        }
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        List<User> users = userService.findAll();

        req.setAttribute("users",users);
        req.getRequestDispatcher("/user.jsp").forward(req,resp);
    }

    private void findOne(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取当前用户的id
        String id = req.getParameter("id");

        User user = userService.findOne(Integer.parseInt(id));

        req.setAttribute("user",user);
        req.getRequestDispatcher("/editUser.jsp").forward(req,resp);
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, NoSuchFieldException, IllegalAccessException, ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //获取参数
        User user = new User();
        Map<String, String[]> map = req.getParameterMap();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {

            if ("action".equals(key)){
                continue;
            }

            //当前页面传递过来该key对应的值
            String value = map.get(key)[0];

            //key其实就是user类中的属性名称
            Field declaredField = User.class.getDeclaredField(key);
            declaredField.setAccessible(true);
            // 对象.setXxx(yy)
            if ("id".equals(key) || "age".equals(key)){
                declaredField.set(user,Integer.parseInt(value));
            }else if("bir".equals(key)){
                declaredField.set(user,sdf.parse(value));
            }else{
                declaredField.set(user,value);
            }
        }

        System.out.println("user: " + user);
        userService.update(user);

        resp.sendRedirect(req.getContextPath() + "/user?action=findAll");
    }

    private void del(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, NoSuchFieldException, IllegalAccessException, ParseException {
        String id = req.getParameter("id");

        userService.del(Integer.parseInt(id));

        resp.sendRedirect(req.getContextPath() + "/user?action=findAll");
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, NoSuchFieldException, IllegalAccessException, ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //获取参数
        User user = new User();
        Map<String, String[]> map = req.getParameterMap();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {

            if ("action".equals(key)){
                continue;
            }

            //当前页面传递过来该key对应的值
            String value = map.get(key)[0];

            //key其实就是user类中的属性名称
            Field declaredField = User.class.getDeclaredField(key);
            declaredField.setAccessible(true);
            // 对象.setXxx(yy)
            if ("id".equals(key) || "age".equals(key)){
                declaredField.set(user,Integer.parseInt(value));
            }else if("bir".equals(key)){
                declaredField.set(user,sdf.parse(value));
            }else{
                declaredField.set(user,value);
            }
        }

        userService.add(user);

        resp.sendRedirect(req.getContextPath() + "/user?action=findAll");
    }
}
